<!-- 来料检验单关联检查项列表+++++++++++++++++++++ -->
<template>
  <div class="index-list-container">
    <!-- 关联检查项卡片 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>关联检查项</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-plus"
          @click="handleAdd"
        >新增</el-button>
      </div>

      <!-- 查询条件 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" style="margin-bottom: 20px">
        <el-form-item label="检测项名称" prop="indexName">
          <el-input v-model="queryParams.indexName" placeholder="请输入检测项名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="检测项编码" prop="indexCode">
          <el-input v-model="queryParams.indexCode" placeholder="请输入检测项编码" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 关联检查项表格 -->
      <el-table
        :data="relatedIndexList"
        border
        size="mini"
        style="width: 100%;"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="index_id" label="检测项ID" width="80"></el-table-column>
        <el-table-column prop="index_name" label="检测项名称" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="index_code" label="检测项编码" width="120" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="检测项类型" width="100">
          <template slot-scope="scope">
            {{ formatIndexType(scope.row.index_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="threshold_max" label="误差上限" width="80"></el-table-column>
        <el-table-column prop="threshold_min" label="误差下限" width="80"></el-table-column>
        <el-table-column prop="unitName" label="单位" width="60"></el-table-column>
        <el-table-column prop="qc_tool" label="检测工具" width="120" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="stander_val" label="标准值" width="80"></el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadRelatedIndexList"
      />
    </el-card>

    <!-- 添加/编辑检查项对话框 -->
    <el-dialog :title="indexDialogTitle" :visible.sync="indexDialogVisible" width="700px" append-to-body>
      <el-form ref="indexForm" :model="indexForm" :rules="indexRules" label-width="120px" size="small" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检测项ID" prop="index_id">
              <el-input v-model="indexForm.index_id" placeholder="点击选择检测项" readonly :disabled="true" class="is-disabled">
                <el-button slot="append" icon="el-icon-search" @click="openIndexSelector"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项名称" prop="index_name">
              <el-input v-model="indexForm.index_name" placeholder="检测项名称" readonly :disabled="true" class="is-disabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检测项编码" prop="index_code">
              <el-input v-model="indexForm.index_code" placeholder="检测项编码" readonly :disabled="true" class="is-disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项类型" prop="index_type">
              <el-input :value="formatIndexType(indexForm.index_type)" placeholder="检测项类型" readonly :disabled="true" class="is-disabled"></el-input>
              <input type="hidden" v-model="indexForm.index_type" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="误差上限" prop="threshold_max">
              <el-input v-model="indexForm.threshold_max" placeholder="误差上限" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="误差下限" prop="threshold_min">
              <el-input v-model="indexForm.threshold_min" placeholder="误差下限" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unitName">
              <el-input v-model="indexForm.unitName" placeholder="单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测工具" prop="qc_tool">
              <el-input v-model="indexForm.qc_tool" placeholder="检测工具"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准值" prop="stander_val">
              <el-input v-model="indexForm.stander_val" placeholder="标准值" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="indexForm.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检测要求" prop="check_method">
          <el-input v-model="indexForm.check_method" type="textarea" placeholder="请输入检测要求"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitIndexForm">确 定</el-button>
        <el-button @click="cancelIndexDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测项选择器对话框 -->
    <el-dialog title="选择检测项" :visible.sync="indexSelectorVisible" width="900px" append-to-body>
      <el-form :model="indexQueryParams" ref="indexQueryForm" size="small" :inline="true">
        <el-form-item label="检测项名称">
          <el-input v-model="indexQueryParams.indexName" placeholder="请输入检测项名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检测项编码">
          <el-input v-model="indexQueryParams.indexCode" placeholder="请输入检测项编码" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleIndexQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetIndexQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="indexSelectorList"
        border
        size="small"
        height="400"
        @row-click="handleRowClick"
        highlight-current-row
        v-loading="selectorLoading"
      >
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="index_id" label="检测项ID" width="80"></el-table-column>
        <el-table-column prop="index_name" label="检测项名称" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="index_code" label="检测项编码" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="检测项类型" width="120">
          <template slot-scope="scope">
            {{ formatIndexType(scope.row.index_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="qc_tool" label="检测工具" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unitName" label="单位" width="80"></el-table-column>
        <el-table-column prop="threshold_max" label="误差上限" width="80"></el-table-column>
        <el-table-column prop="threshold_min" label="误差下限" width="80"></el-table-column>
        <el-table-column prop="stander_val" label="标准值" width="80"></el-table-column>
      </el-table>

      <!-- 检测项选择器分页 -->
      <pagination
        v-show="selectorTotal > 0"
        :total="selectorTotal"
        :page.sync="indexQueryParams.pageNum"
        :limit.sync="indexQueryParams.pageSize"
        @pagination="loadIndexSelectorList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="indexSelectorVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectIndex">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectQcTemplateIndexList } from '@/api/qc/QualitySchemeOrder';
import { selectQcIqcLineByIqcId, insertQcIqcLine, updateQcIqcLine, deleteQcIqcLineByLineId } from '@/api/qc/IncomingInspection';
import Pagination from '@/components/Pagination';

export default {
  name: "RelatedIndexList",
  components: {
    Pagination
  },
  props: {
    // 当前IQC的ID
    iqcId: {
      type: [Number, String],
      default: null
    },
    // 模板ID
    templateId: {
      type: [Number, String],
      default: null
    },
    // 是否为编辑模式
    isEdit: {
      type: Boolean,
      default: false
    },
    // 是否为只读模式
    readOnly: {
      type: Boolean,
      default: false
    },
    // 是否禁用所有操作
    disableAll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 加载状态
      loading: false,
      selectorLoading: false,
      // 关联检查项列表相关数据
      relatedIndexList: [],
      total: 0,
      queryParams: {
        indexName: '',
        indexCode: '',
        pageNum: 1,
        pageSize: 10
      },

      // 检查项表单相关数据
      indexDialogVisible: false,
      indexDialogTitle: '',
      indexForm: {
        line_id: null,
        index_id: null,
        index_name: '',
        index_code: '',
        index_type: '',
        threshold_max: null,
        threshold_min: null,
        unitName: '',
        qc_tool: '',
        check_method: '',
        stander_val: null,
        remark: ''
      },
      indexRules: {
        index_id: [{ required: true, message: '请选择检测项', trigger: 'blur' }],
      },

      // 检测项选择相关数据
      indexSelectorVisible: false,
      indexSelectorList: [],
      selectorTotal: 0,
      indexQueryParams: {
        indexName: '',
        indexCode: '',
        pageNum: 1,
        pageSize: 5
      },
      selectedIndex: null,

      // 行操作状态标识
      isAddOperation: true
    };
  },
  watch: {
    iqcId: {
      handler(val) {
        if (val) {
          this.loadRelatedIndexList();
        }
      },
      immediate: true
    }
  },
  methods: {
    // 加载关联检查项列表
    loadRelatedIndexList() {
      if (!this.iqcId) return;

      this.loading = true;
      // 调用后端API获取关联检查项数据，确保字段名与后端实体类严格一致
      const queryParams = {
        iqcId: this.iqcId,
        indexName: this.queryParams.indexName || '',
        indexCode: this.queryParams.indexCode || '',
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      };

      // 打印查询参数，用于调试
      console.log('查询检测项的参数:', queryParams);

      selectQcIqcLineByIqcId(queryParams).then(response => {
        if (response.code === 200) {
            // 将后端数据字段名转换为前端使用的字段名
            this.relatedIndexList = (response.rows || []).map(item => ({
                line_id: item.lineId,
                index_id: item.indexId,
                index_name: item.indexName,
                index_code: item.indexCode,
                index_type: item.indexType,
                threshold_max: item.thresholdMax,
                threshold_min: item.thresholdMin,
                unitName: item.unitName,
                qc_tool: item.qcTool,
                check_method: item.checkMethod,
                stander_val: item.standerVal,
                remark: item.remark
            }));
            this.total = response.total || 0;
            console.log("获取检测单关联检查项列表成功", this.relatedIndexList);
        } else {
          this.relatedIndexList = [];
          this.$message.error("获取检查项列表失败");
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取检测单关联检查项列表异常", error);
        this.$message.error("获取检查项列表失败");
        // 加载失败时使用模拟数据（仅开发阶段使用）
        this.loadMockRelatedIndexList();
        this.loading = false;
      });
    },

    // 查询按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.loadRelatedIndexList();
    },

    // 重置查询操作
    resetQuery() {
      this.queryParams = {
        indexName: '',
        indexCode: '',
        pageNum: 1,
        pageSize: 10
      };
      this.handleQuery();
    },

    // 新增按钮操作
    handleAdd() {
      this.isAddOperation = true;
      this.indexDialogTitle = '添加关联检查项';
      this.resetIndexForm();
      this.indexDialogVisible = true;
    },

    // 编辑按钮操作
    handleEdit(row) {
      this.isAddOperation = false;
      this.indexDialogTitle = '编辑关联检查项';
      this.resetIndexForm();
      this.indexForm = JSON.parse(JSON.stringify(row));
      this.indexDialogVisible = true;
    },

    // 删除按钮操作
    handleDelete(row) {
      this.$confirm('是否确认删除该关联检查项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API
        deleteQcIqcLineByLineId(row.line_id).then(response => {
          if (response === true || response.code === 200) {
            this.$message.success('删除成功');
            this.loadRelatedIndexList();
          } else {
            this.$message.error(typeof response === 'string' ? response : (response.msg || '删除检查项失败'));
          }
        }).catch(error => {
          console.error("删除检查项异常", error);
          this.$message.error('删除检查项失败: ' + (error.message || '服务器错误'));
        });
      }).catch(() => {});
    },

    // 提交检查项表单
    submitIndexForm() {
      this.$refs.indexForm.validate(valid => {
        if (valid) {
          // 转换为后端需要的字段格式
          // 确保iqcId被正确传递，转为字符串类型避免类型转换问题
          const data = {
            iqcId: String(this.iqcId),
            indexId: String(this.indexForm.index_id),
            indexName: this.indexForm.index_name,
            indexCode: this.indexForm.index_code,
            indexType: String(this.indexForm.index_type),
            thresholdMax: this.indexForm.threshold_max,
            thresholdMin: this.indexForm.threshold_min,
            unitName: this.indexForm.unitName,
            qcTool: this.indexForm.qc_tool,
            checkMethod: this.indexForm.check_method,
            standerVal: this.indexForm.stander_val,
            remark: this.indexForm.remark
          };

          console.log("提交的检查项数据:", data); // 添加日志，便于调试

          this.loading = true;
          if (this.isAddOperation) {
            // 新增操作
            insertQcIqcLine(data).then(response => {
              if (response === true || response.code === 200) { // 根据返回值类型判断
                this.$message.success('新增检查项成功');
                this.indexDialogVisible = false;
                this.loadRelatedIndexList();
              } else {
                this.$message.error(typeof response === 'string' ? response : (response.msg || '新增检查项失败'));
              }
              this.loading = false;
            }).catch(error => {
              console.error("新增检查项异常", error);
              this.$message.error('新增检查项失败: ' + (error.message || '服务器错误'));
              this.loading = false;
            });
          } else {
            // 编辑操作
            // 需要添加lineId参数
            if (this.indexForm.line_id) {
              data.lineId = this.indexForm.line_id;
            }

            updateQcIqcLine(data).then(response => {
              if (response === true || response.code === 200) {
                this.$message.success('修改检查项成功');
                this.indexDialogVisible = false;
                this.loadRelatedIndexList();
              } else {
                this.$message.error(typeof response === 'string' ? response : (response.msg || '修改检查项失败'));
              }
              this.loading = false;
            }).catch(error => {
              console.error("修改检查项异常", error);
              this.$message.error('修改检查项失败: ' + (error.message || '服务器错误'));
              this.loading = false;
            });
          }
        }
      });
    },

    // 取消检查项对话框
    cancelIndexDialog() {
      this.indexDialogVisible = false;
      this.resetIndexForm();
    },

    // 重置检查项表单
    resetIndexForm() {
      this.indexForm = {
        line_id: null,
        index_id: null,
        index_name: '',
        index_code: '',
        index_type: '',
        threshold_max: null,
        threshold_min: null,
        unitName: '',
        qc_tool: '',
        check_method: '',
        stander_val: null,
        remark: ''
      };
      if (this.$refs.indexForm) {
        this.$refs.indexForm.resetFields();
      }
    },

    // 打开检测项选择器
    openIndexSelector() {
      this.indexSelectorVisible = true;
      this.selectedIndex = null;
      this.loadIndexSelectorList();
    },

    // 加载检测项选择器数据
    loadIndexSelectorList() {
      // 这里应该调用后端API获取所有检测项，目前使用模拟数据
      // 如果有templateId，则应该根据模板ID获取关联的检测项
      if (this.templateId) {
        this.indexSelectorList = [];
        this.selectorLoading = true;
        // 构建查询参数 - 使用后端实体类字段名
        const queryParams = {
          index_name: this.indexQueryParams.indexName || '',
          index_code: this.indexQueryParams.indexCode || '',
          pageNum: this.indexQueryParams.pageNum,
          pageSize: this.indexQueryParams.pageSize
        };

        selectQcTemplateIndexList(this.templateId, queryParams).then(response => {
          if (response.code === 200) {
            this.indexSelectorList = response.rows || [];
            this.selectorTotal = response.total || 0;
            console.log("获取模板关联检测项列表成功", this.indexSelectorList);
          }
          this.selectorLoading = false;
        }).catch(error => {
          console.error("获取模板关联检测项列表异常", error);
          this.$message.error("获取检测项数据失败");
          // 使用模拟数据作为备选
          this.loadMockIndexSelectorData();
          this.selectorLoading = false;
        });
      } else {
        // 无模板ID时使用模拟数据
        this.loadMockIndexSelectorData();
      }
    },

    // 加载模拟的检测项选择器数据
    loadMockIndexSelectorData() {
      setTimeout(() => {
        this.indexSelectorList = [
          {
            index_id: 1,
            index_name: '尺寸检测',
            index_code: 'CC001',
            index_type: '尺寸',
            threshold_max: 10.5,
            threshold_min: 9.5,
            unitName: 'mm',
            qc_tool: '卡尺',
            check_method: '测量产品长度',
            stander_val: 10,
            remark: '关键尺寸'
          },
          {
            index_id: 2,
            index_name: '重量检测',
            index_code: 'ZL001',
            index_type: '重量',
            threshold_max: 105,
            threshold_min: 95,
            unitName: 'g',
            qc_tool: '电子秤',
            check_method: '测量产品重量',
            stander_val: 100,
            remark: ''
          },
          {
            index_id: 3,
            index_name: '硬度测试',
            index_code: 'YD001',
            index_type: '硬度',
            threshold_max: 65,
            threshold_min: 55,
            unitName: 'HRC',
            qc_tool: '硬度计',
            check_method: '测量产品硬度',
            stander_val: 60,
            remark: '表面硬度'
          }
        ];
      }, 300);
    },

    // 检测项查询操作
    handleIndexQuery() {
      this.loadIndexSelectorList();
    },

    // 重置检测项查询
    resetIndexQuery() {
      this.indexQueryParams = {
        indexName: '',
        indexCode: '',
        pageNum: 1,
        pageSize: 5
      };
      this.handleIndexQuery();
    },

    // 行点击事件
    handleRowClick(row) {
      this.selectedIndex = row;
    },

    // 确认选择检测项
    confirmSelectIndex() {
      if (!this.selectedIndex) {
        this.$message.warning('请选择一个检测项');
        return;
      }

      // 将选中的检测项数据填充到表单中
      this.indexForm = {
        ...this.indexForm,
        index_id: this.selectedIndex.index_id,
        index_name: this.selectedIndex.index_name,
        index_code: this.selectedIndex.index_code,
        index_type: this.selectedIndex.index_type,
        threshold_max: this.selectedIndex.threshold_max,
        threshold_min: this.selectedIndex.threshold_min,
        unitName: this.selectedIndex.unitName,
        qc_tool: this.selectedIndex.qc_tool,
        check_method: this.selectedIndex.check_method,
        stander_val: this.selectedIndex.stander_val,
        remark: this.selectedIndex.remark
      };

      this.indexSelectorVisible = false;
    },

    // 加载模拟关联检查项数据（用于开发阶段）
    loadMockRelatedIndexList() {
      setTimeout(() => {
        this.relatedIndexList = [
          {
            index_id: 1,
            index_name: '尺寸检测',
            index_code: 'CC001',
            index_type: '尺寸',
            threshold_max: 10.5,
            threshold_min: 9.5,
            unitName: 'mm',
            qc_tool: '卡尺',
            check_method: '测量产品长度',
            stander_val: 10,
            remark: '关键尺寸'
          },
          {
            index_id: 2,
            index_name: '重量检测',
            index_code: 'ZL001',
            index_type: '重量',
            threshold_max: 105,
            threshold_min: 95,
            unitName: 'g',
            qc_tool: '电子秤',
            check_method: '测量产品重量',
            stander_val: 100,
            remark: ''
          }
        ];
      }, 300);
    },

    // 格式化检测项类型，将数字转换为对应的文字描述
    formatIndexType(type) {
      const typeMap = {
        '1': '外观',
        '2': '视觉',
        '3': '尺寸',
        '4': '物理性能检测',
        '5': '化学成分检测'
      };
      return typeMap[type] || type;
    }
  }
};
</script>

<style scoped>
.index-list-container {
  padding: 10px 0;
}

.box-card {
  margin-bottom: 20px;
}

.box-card .el-card__header {
  padding: 12px 20px;
}

.is-disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>
